var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var check = require('../../utils/check.js');
var user = require('../../utils/user.js');
var api = require('../../config/api.js');

Page({
  data: {
    lock:false,
    fileList: [],
    purchaseList: [],
    quote: {
      id: 0,
      itemId: 0,
      herbId: 0,
      supplyPrice: '',
    },
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    let purchaseListStr = wx.getStorageSync('purchaseListStr');
    if (purchaseListStr) {
      let purchaseList = JSON.parse(purchaseListStr);
      let quote = purchaseList.map((t) => {
        let q = {
          id: 0,
          supplyPrice: '',
          itemId: t.itemId,
          herbId: t.herbId,
          herbName: t.herbName,
          specifications: t.specifications,
          genericName: t.genericName,
          describe:t.describe,
          measurementUnit:t.measurementUnit,
          needAmount: t.needAmount,
          herbImage: t.herbImage || '/static/images/herb_icon.png',
          num: purchaseList.length
        }
        return q;
      })[0];
      quote.supplyPrice = this.data.quote.supplyPrice || '';
      this.setData({
        purchaseList: purchaseList,
        quote: quote
      });
      // console.log(quote);
    }
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    this.upload(file);
  },
  upload: function (file) {
    var that = this;
    wx.showLoading({
      title: '上传中...',
      mask: true
    });
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: file.url,
      name: 'file',
      success: function (res) {
        wx.hideLoading();
        // console.log(res)
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          // 上传完成需要更新 fileList
          var url = _res.data.url
          const {
            fileList = []
          } = that.data;
          fileList.push({
            ...file,
            url: url
          });
          that.setData({
            fileList
          });
        }
      },
      fail: function (e) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  fileDelete(event) {
    const {
      index
    } = event.detail;
    let fileList = this.data.fileList;
    fileList.splice(index, 1)
    this.setData({
      fileList
    });
  },

  bindinputSupplyPrice(event) {
    let quote = this.data.quote;
    quote.supplyPrice = event.detail.value;
    this.setData({
      quote: quote
    });
  },
  // submitQuote(){
  //   //测试
  //   this.navigateToPurchase(2, '已报价')
  // },
  submitQuote() {
    let {lock} = this.data;
    let quote = this.data.quote;
    if(lock){
      util.showErrorToast('请不要重复提交');
      return false;
    }

    if (quote.supplyPrice == '') {
      util.showErrorToast('请输入报价');
      return false;
    }
    if(!check.isValidMoney(quote.supplyPrice)){
      wx.showModal({
        title: '错误信息',
        content: '报价仅支持小数点前8位，小数点后2位格式',
        showCancel: false
      });
      return false;
    }

    if (this.data.fileList.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '请上传药材规格图片',
        showCancel: false
      });
      return false;
    }
    let specificationsImage = '';
    if (this.data.fileList) {
      specificationsImage = this.data.fileList.map((t) => t.url).join(',')
    }

    let quotePriceList = this.data.purchaseList.map((t) => {
      let quotePrice = {
        // herbId: quote.herbId,
        herbId:t.herbId,
        supplyPrice: quote.supplyPrice,
        specificationsImage: specificationsImage,

        supplyContactName: t.contactName,
        supplyContactTel: t.contactTel,
        formPurchaseItemId: t.itemId,
        specificationsText: t.specifications,

      };
      return quotePrice;
    });

    let that = this;
    that.setData({lock:true});
    wx.request({
      url: api.QuoteSave,
      data: quotePriceList,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.errno == 0) {
          user.TipsRequestSubscribeMessage(function () {
            that.navigateToPurchase(2, '已报价')
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  navigateToPurchase(type, name) {
    wx.setStorageSync('purchase_type', type)
    wx.setStorageSync('purchase_name', name);
    wx.navigateTo({
      url: "/pages/purchase/purchase"
    });
  },
})